from django.shortcuts import render,redirect,reverse
from .utils import  aliyunsms
from django .core.cache import cache
# Create your views here.
import json
from django.views import View
from django.http import JsonResponse,HttpResponse
from django.contrib import auth
import re
from .models import UserProfile
from django.core.mail import send_mail
from .models import EmailVerifyRecord,Article
from  .froms import RegisterForm
# make_password引入密码加密的函数
from django.contrib.auth.hashers import make_password
from index.utils.email_send import send_register_email
from BWYG import settings
from itsdangerous import URLSafeSerializer,TimedJSONWebSignatureSerializer
import itsdangerous

class Regist_Api(View):    #注册接口

    def post(self,request):
        #获取前端传来的数据
        username=json.loads(request.body)["data"]["username"]
        pwd=json.loads(request.body)["data"]["pwd"]
        email=json.loads(request.body)["data"]["email"]
        # print(pwd)
        #进行正则匹配
        u= re.match(r"^[a-zA-Z0-9_-]{3,16}$",username)
        p=re.match(r"^[a-zA-Z0-9_-]{6,18}$",pwd)
        e=re.match(r"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$",email)


        if u and p and e:
            if UserProfile.objects.filter(username=username):
                data = {
                    "data": {
                        'status': 4004,
                        'msg': '用户名已存在'
                    }
                }
                return JsonResponse(data)
            UserProfile.objects.create_user(username=username, password=pwd,email=email)

            data={
                "data":{
                'status':200,
                'msg':'注册成功'
            }
            }

            return JsonResponse(data)

        elif u and p and not e:

            data = {
                "data": {
                'status': 4001,
                'msg': '邮箱不规范'
            }}

            return JsonResponse(data)

        elif u and e and not p:

            data = {
                "data": {
                'status': 4002,
                'msg': '密码不规范'
            }}

            return JsonResponse(data)

        elif p and e and not u:

            data = {
                "data": {
                "status": 4003,
                "msg": "用户名不规范"
            }}

            return JsonResponse(data)


class Login_Api(View):    #登录接口

    def post(self,request):

        username=json.loads(request.body,encoding='utf-8')["data"]["username"]
        password=json.loads(request.body,encoding='utf-8')["data"]["pwd"]
        user=auth.authenticate(username=username,password=password)
        if user:
                auth.login(request,user)
                data={
                    "data":{
                        "status":4003,
                        "msg":"密码错误"
                    }}
                return JsonResponse(data)
        elif user is None:
            data = {
                "data": {
                    "status": 4004,
                    "msg": "用户不存在"
                }
            }
            return JsonResponse(data)
        else:
            data1={
                    "data":{
                        "status":4002,
                        "msg":"登录成功"
                    }
                }
            return JsonResponse(data1)



class RegisterView(View):     #发送邮件接口
    """邮箱注册"""

    def post(self, request):
        user = json.loads(request.body)["username"]
        pwd=json.loads(request.body)["pwd"]
        email=json.loads(request.body)["email"]
        salt = settings.SECRET_KEY
        t = itsdangerous.TimedJSONWebSignatureSerializer(salt, expires_in=600)
        res = t.dumps({"username": user,"pwd":pwd,"email":email})
        token = res.decode()
        #print(token)

        email = send_mail(
            "你好",
            "请点击:http://127.0.0.1:8000/register?key={}激活".format(token),
            settings.EMAIL_HOST_USER,
            ["1610839396@qq.com"]
        )
        print(email)

        if email == 1:
            return JsonResponse({"status": "200", "msg": "发送成功"})
        else:
            return JsonResponse({"status": "404", "msg": "发送失败"})

    def get(self, request):
        data = request.GET.get('key')
        salt = settings.SECRET_KEY
        t = itsdangerous.TimedJSONWebSignatureSerializer(salt)
        res = t.loads(data)
        print(res)
        return JsonResponse({"status": "200", "msg": "激活成功"})


class registerView(View):
    """邮箱注册"""
    def get(self,request):
        return render(request,'index1.html')
    def post(self, request):
        register_form=RegisterForm(request.POST)
        if register_form.is_valid():
            user_name=request.POST.get('user','')
            email=request.POST.get('email','')
            pass_word=request.POST.get('pwd','')
            u=UserProfile.objects.filter(username=user_name).count()
            e=UserProfile.objects.filter(email=email).count()
            if u or e:
                return HttpResponse('{"status":"该用户名或邮箱已被占用！"}')
            else:
                user_profile=UserProfile()
                user_profile.username=user_name
                user_profile.email=email
                user_profile.password=make_password(pass_word)
                user_profile.is_active=False
                user_profile.save()
                send_register_email(email, 'register')
                return  redirect(to=reverse('index:registe'))
        msg=register_form.errors
        msg=json.dumps(msg)
        return HttpResponse(msg)


class ActiveUserView(View):
    """激活账户"""

    def get(self, request, code):
        all_records = EmailVerifyRecord.objects.filter(code=code)
        if all_records:
            for record in all_records:
                email = record.email
                user = UserProfile.objects.get(email=email)
                user.is_active = True
                user.save()

        return render(request, 'index1.html')

class PhoneCode(View):

    # 手机短信接口
    def post(self, request):
        # http://127.0.0.1:8000/api/send/
        # 获取手机号
        phone = json.loads(request.body)["phone"]
        # phone = 18434288349
        # 生成6位验证码
        code = aliyunsms.get_code(6, False)
        # 缓存到Redis
        cache.set(phone, code, 60)  # 60s有效期
        print("判断是否存在:", cache.has_key(phone))
        print("获取Redis验证码:", cache.get(phone))
        # 发短信
        result = aliyunsms.send_sms(phone, code)
        return JsonResponse({"status": "200", "msg": result})

    # 短信验证码校验
    def get(self, request, restful=None):
        # 1.获取电话和手动输入的验证码
        phone = request.GET.get('phone')
        code = request.GET.get('code')
        # phone = 15835176962
        # code = 123456
        # 2.获取Redis中保存的code
        print('缓存中是否包含:', cache.has_key(phone))
        print("取值:", cache.get(phone))
        cache_code = cache.get(phone)
        # 3.判断
        if code == cache_code:
            return restful.ok("OK")
        else:
            return restful.page_error("验证码错误", data=None)


class article(View):#商品接口
    def get(self,request):
        article_all=Article.objects.all()
        article_list=[]
        for article in article_all:
            article_list.append(article.to_dict())
        return JsonResponse({"data":article_list})
            
    def post(self,request):
        data=json.loads(request.body)
        if Article.objects.filter(article_title=data["title"]):
            return JsonResponse({"msg":"fail to save! Commodity repeat"})
        else:
            shop=Article()
            shop.article_title=data["title"]
            shop.article_price=data["price"]
            shop.article_PCS=data["pcs"]
            shop.article_img=data["img"]
            shop.article_state=data["state"]
            shop.save()
            return JsonResponse({"msg":"save success!"})
            
        
class search(View): #搜索功能
    def get(self,request):
        return render(request,'search.html')
    def post(self,request):
        keyword=request.POST.get("keyword","")
        shop_list=Article.objects.filter(article_title__icontains=keyword)
        print(shop_list)
        if not shop_list:
            data={
                "msg":"搜索结果不存在"
            }
            return render(request,'search.html',context=data)
        else:
            return render(request,'search.html',{"shop_list":shop_list})


